from django.shortcuts import render
from django.http import HttpResponse,JsonResponse

from .. models import Goods,Types

from . TypesViews import GetTypesAll
from . UserViews import uploads
from web.settings import BASE_DIR
import time,random,os


# 商品列表
def index(request):


	# 获取所有的商品
	obs = Goods.objects.filter()


	# 获取搜索的类型
	types = request.GET.get('type',None)
	# 判断是否有搜索条件
	if types:
		# 获取搜索的关键字
		keywords = request.GET.get('keywords')
		# 判断搜索类型是否为sex
		if types == 'sex':
			sexlist = {'男':'1','女':'0'}
			obs = obs.filter(sex=sexlist[keywords])
		else:
			# 拼接条件参数
			data = {types+'__contains':keywords}
			# 执行条件搜索
			obs = obs.filter(**data) 

	# 数据分页
	# 获取当前页的页数
	pageindex = request.GET.get('p',1)
	# 导入分页类
	from django.core.paginator import Paginator
	# 实例化分页对象
	p = Paginator(obs, 5)

	# 获取当前页的 数据
	goodslist = p.page(pageindex)

	# 分配数据
	context = {'goodslist':goodslist}

	# 加载模板-
	return render(request,'admin/goods/index.html',context)

# 商品添加页面
def add(request):
	
	# 分配数据
	context = {'typelist':GetTypesAll(request)}

	# 加载模板-
	return render(request,'admin/goods/add.html',context)
# 执行商品添加
def insert(request):

	# 获取数据
	data = request.POST.dict()

	del data['csrfmiddlewaretoken']

	# 判断是否有文件上传
	myfile = request.FILES.get('pic',None)
	# myfile = request.FILES.getall()

	if myfile:
		# 上传图片 uploads
		data['pic'] = uploads(myfile)
	else:
		return HttpResponse('<script>alert("必须上传图片");history.back(-1);</script>')


	# 创建时,外键的值 要求是个对象
	data['tid'] = Types.objects.get(id=data['tid'])

	# 执行添加
	res = Goods.objects.create(**data)

	if res:
		return HttpResponse('<script>alert("商品添加成功");location.href="/myadmin/goods/index/"</script>')
	else:
		return HttpResponse('<script>alert("商品添加失败");history.back(-1)"</script>')



# 执行商品删除
def delete(request):

	if request.is_ajax():
		try:
			# 获取id,执行逻辑删除
			ob = Goods.objects.get(id=request.GET['id'])
			# ob.nmb = True
			ob.status = 3
			ob.save()
			return JsonResponse({'code':1,'msg':'删除成功'})
		except:
			return JsonResponse({'code':0,'msg':'删除失败'})
	else:
		# 返回一个404的错误页面
		raise Http404("Poll does not exist")

# 商品编辑
def edit(request,gid):
	# 获取商品信息
	ob = Goods.objects.get(id=gid)

	# 分配数据
	context = {'ginfo':ob}
	# 加载模板
	return render(request,'admin/goods/edit.html',context)

# 执行商品的更新
def update(request):

	# 获取数据
	data = request.POST.dict()
	print(data)
	del data['csrfmiddlewaretoken']

	# 获取会员对象
	ob = Goods.objects.get(id=data['id'])
	ob.info = data['info']
	ob.title = data['title']
	ob.price = data['price']
	ob.store = data['store']
	ob.pic = data['pic']
	ob.status = data['status']


	# 判断是否更新了头像
	myfile = request.FILES.get('pic',None)
	if myfile:

		# 删除原来的头像
		try:
			os.remove(BASE_DIR+ob.pic)#/static/pics/a.jpg
		except:
			pass
		# 上传新的头像
		ob.pic  = uploads(myfile)

		# ob.pic = data['pic']

	# 执行更新
	ob.save()

	return HttpResponse('<script>alert("更新成功");location.href="/myadmin/user/index/"</script>')


# 图片上传
def uploads(myfile):

	# 获取文件的后缀名
	h = myfile.name.split('.').pop()
	arr = ['jpg','png','gif','jpeg']
	# 判断上传的文件类型
	if h not in arr:
		return False

	# 重新定义新的文件名 时间搓+随机数
	filename = str(time.time())+str(random.random())+'.'+h

	# 执行文件上传
	destination = open(BASE_DIR+"/static/pics/"+filename,"wb+")

	for chunk in myfile.chunks():      # 分块写入文件  
		destination.write(chunk)  
	destination.close()

	# 返回文件路径和文件名
	return '/static/pics/'+filename